package com.xxl.job.framework.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 国际化 （获取请求国际化参数应用对应的国际化文件）
 *
 * @author : zyc
 * @version : 1.0
 * @date : 2021-08-04
 */
@Configuration
public class LocaleResolverConfig implements LocaleResolver {

    /**
     * 根据请求 local 参数获取国际化值，应用国际化 .properties 文件
     *
     * @param httpServletRequest
     * @return java.util.Locale
     * @author: zyc
     * @dateTime: 2021/8/4 16:33
     */
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.getParameter("local");
        // 如果存在区域信息
        if (!StringUtils.isEmpty(l)) {
            // 字符串分割 s[0]:zh(中文) s[1]:CN(中国)
            String[] s = l.split("_");
            return new Locale(s[0], s[1]);
        }
        // 使用浏览器默认的语言
        return Locale.getDefault();
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    }

    /**
     * 注册国际化组件
     *
     * @author: zyc
     * @return: org.springframework.web.servlet.LocaleResolver
     * @date: 2021/11/26
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new LocaleResolverConfig();
    }
}
